#!/usr/bin/evn python

import wsgiref.handlers
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.api import urlfetch


from models import *
from ptzmodels import *
from common.constants import *

import string

webapp.template.register_template_library('common.customtags')

class Statistics(webapp.RequestHandler):
    def get(self):
        from google.appengine.api import users
        
        user = users.get_current_user()
        if not user or user.nickname() not in ADMIN_EMAILS:
            loginURL = users.create_login_url("/")
            values = {
                'error' : loginURL
            }
            self.response.out.write(template.render(TEMPLATE_DIRECTORY + 'home.html', values))
            return
        
        action = self.request.get('action')
        sceneStart = self.request.get('start')
        sceneEnd = self.request.get('end')
        nFetch = int(sceneEnd) - int(sceneStart) + 1;
        if action == 'avError':
            
            scenes = Scene.all().filter('index <=', int(sceneEnd)).filter('index >=', int(sceneStart)).fetch(nFetch)
            for scene in scenes:
                if scene.calibrated:
                    corrs = Correspondence.all().filter('scene =', scene)
                    errSum = 0
                    errCount = 0
                    for corr in corrs:
                        errSum = errSum + corr.pixelProjectionError
                        errCount = errCount + 1
                    err = float(errSum) / float(errCount);
                    self.response.out.write(str(scene.index) + ' ' + str(err) + '\n')
        
        if action == 'ptzObservation':
            from ptzmodels import PTZScene, UserObservation
            ptzScenes = PTZScene.all()
            for s in ptzScenes:
                observations = UserObservation.all().filter('scene =', s)
                self.response.out.write('Scene ' + str(s.index) + ':\n')
                for o in observations:
                    self.response.out.write(str(o.clockIn) + ' ' + str(o.clockOut) + ' ' + str(o.numberOfClicks) + ' ' + str(o.numberOfCorrespondences) + '\n')
            
                
        if action == 'latlongdump':
            from ptzmodels import PTZScene, PTZCorrespondence
            scene = PTZScene.get_by_key_name('ptzscene' + str(sceneStart))
            if scene:
                corrs = PTZCorrespondence.all().filter('scene =', scene)
                for c in corrs:
                    self.response.out.write(str(c.latitude) + ',' + str(c.longitude) + ',' + str(c.altitude) + '\n')
                    
        if action == 'longlatdump':
            from ptzmodels import PTZScene, PTZCorrespondence
            scene = PTZScene.get_by_key_name('ptzscene' + str(sceneStart))
            if scene:
                corrs = PTZCorrespondence.all().filter('scene =', scene)
                for c in corrs:
                    self.response.out.write(str(c.longitude) + ',' + str(c.latitude) + ',' + str(c.altitude) + '\n')
                    
                    
class PublishStatistics(webapp.RequestHandler):
    def get(self):
        from google.appengine.api import users
        
        user = users.get_current_user()
        if not user or user.nickname() not in ADMIN_EMAILS:
            loginURL = users.create_login_url("/")
            values = {
                'error' : loginURL
            }
            self.response.out.write(template.render(TEMPLATE_DIRECTORY + 'home.html', values))
            return
      
        allOwnedScenes = Scene.all().filter('owner !=', None).fetch(1000);
        allNotMeScenes = Scene.all().filter('owner !=', None).filter('owner !=', user).fetch(1000);
        allOwnedCorrs = Correspondence.all().filter('owner !=', None).fetch(1000);
        allNotMeCorrs = Correspondence.all().filter('owner !=', None).filter('owner !=', user).fetch(1000);
        allOwnedMeshes = Mesh.all().filter('owner !=', None).fetch(1000);
        allNotMeMeshes = Mesh.all().filter('owner !=', None).filter('owner !=', user).fetch(1000);
        
        allCalibs = Calibration.all().fetch(1000);
        numOwnedCalibs = 0;
        numNotMeCalibs = 0;
        for s in allOwnedScenes:
            if s.calibrated:
              numOwnedCalibs = numOwnedCalibs + 1;
        for s in allNotMeScenes:
          if s.calibrated:
              numNotMeCalibs = numNotMeCalibs + 1;
    

        gc = GlobalCounter.get_by_key_name('gc')

        outstr = '<h1>Total:</h1>'
        outstr = outstr + str(gc.numCorrespondences) + ' correspondences<br/>' + str(gc.numMeshes) + ' meshes<br/>' + \
                            str(gc.numScenes) + 'scenes<br/>' + str(len(allCalibs)) + ' calibrations<br/>'

        outstr = outstr + '<h1>Owned:</h1>'
        outstr = outstr + str(len(allOwnedCorrs)) + ' correspondences<br/>' + str(len(allOwnedMeshes)) + ' meshes<br/>' + \
                            str(len(allOwnedScenes)) + 'scenes<br/>' + str(numOwnedCalibs) + ' calibrations<br/>'

        outstr = outstr + '<h1>Owned and not me</h1>'
        outstr = outstr + str(len(allNotMeCorrs)) + ' correspondences<br/>' + str(len(allNotMeMeshes)) + ' meshes<br/>' + \
                            str(len(allNotMeScenes)) + 'scenes<br/>' + str(numNotMeCalibs) + ' calibrations<br/>'

        self.response.out.write(outstr)